package systemConfigModel

import (
	"arabApi/app/api/models"
	"arabApi/app/api/requests/systemConfigRequest"
	"arabApi/pkg/database"
	"arabApi/pkg/helpers"
	"errors"
	"github.com/spf13/cast"
)

// User 用户模型
type SystemConfig struct {
	models.BaseModel
	ParentId  int64  `json:"parent_id,omitempty"`
	Title     string `json:"title,omitempty"`
	Key       string `json:"key"`
	Value     string `json:"value"`
	State     string `json:"state" gorm:"default:1"`
	StateName string `json:"stateName" gorm:"-"`
	Operator  int    `json:"operator" gorm:"column:operator_id"`
	models.CommonTimestampsField
}

func (t SystemConfig) TableName() string {
	return "tp_system_config"
}

func List(req systemConfigRequest.SystemConfigRequest) ([]SystemConfig, int64) {

	var count int64
	dd := database.DB.Model(SystemConfig{})

	var systemConfig1 []SystemConfig
	p := cast.ToInt(req.Page)
	ps := cast.ToInt(req.PageSize)

	if helpers.Empty(req.Key) == false {
		dd = dd.Where("`key` = ?", req.Key)
	}

	if helpers.Empty(req.Title) == false {
		dd = dd.Where("title = ?", req.Title)
	}

	if helpers.Empty(req.State) == false {
		dd = dd.Where("state = ?", req.State)
	}

	dd.Count(&count).Limit(ps).Offset((p - 1) * ps).Find(&systemConfig1)
	return systemConfig1, count
}

func GetMsgById(id int64) SystemConfig {
	var systemConfig1 SystemConfig
	database.DB.Model(SystemConfig{}).Where("id = ?", id).Find(&systemConfig1)
	return systemConfig1
}

func ListCount() int64 {
	var count int64
	database.DB.Count(&count)
	return count
}

func Add(add systemConfigRequest.SysAdd) uint64 {
	ee := &SystemConfig{}
	if err := helpers.Copy(add, ee); err != nil {
		return 0
	}

	database.DB.Create(ee)
	return ee.ID
}

func Update(add systemConfigRequest.SysAdd) error {
	ee := &SystemConfig{}
	if err := helpers.Copy(add, ee); err != nil {
		return errors.New("转化错误")
	}

	res := database.DB.Where("id = ?", add.Id).Updates(ee)
	return res.Error
}

func Del(id int64) error {
	var systemConfig1 int
	ccc := database.DB.Where("id = ?", id).Delete(&systemConfig1)
	return ccc.Error
}
